package com.netty.service;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.AttributeKey;

/**
 * @author: cxt
 * @time: 2021/8/12
 * netty 客户端
 * 要启动一个Netty客户端，必须要指定三类属性，分别是线程模型、IO 模型、连接读写处理逻辑、绑定端口
 */
public class NettyClient {
    private final static int Max = 5; // 重新次数

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(group) // 1、指定线程模型
                // 2、指定IO类型为NIO
                .channel(NioSocketChannel.class)
                // 可选：可以给客户端 Channel，也就是NioSocketChannel绑定自定义属性,可以通过channel.attr()取出这个属性
                .attr(AttributeKey.newInstance("clientName"), "nettyClient")
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000) // 可选：设置TCP底层属性，连接超时时间
                .option(ChannelOption.SO_KEEPALIVE, true)
                .option(ChannelOption.TCP_NODELAY, true)
                // 3、IO处理逻辑
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(new NettyClientHandle()); // 发送消息处理类
                    }
                });
        // 4.建立连接
        ChannelFuture f = bootstrap.connect("127.0.0.1", 2019).addListener(future -> {
            if (future.isSuccess()) {
                System.out.println("连接成功");
            }
        }).sync();

        // 关闭
        f.channel().closeFuture().sync();
    }

}
